//
//  FYOAuthViewController.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/9.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

//  微博AppKey
let WeiboAppKey = "3927478978"
//  微博AppSecret
let WeiboAppSecret = "e684362d60aa8c9efd79e635fb63f1ff"
//  授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"

class FYOAuthViewController: UIViewController {
    
    // MARK: -- 懒加载
    private lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  改成透明的
        webView.opaque = false

        //  设置代理
        webView.delegate = self
        view = webView
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setNavUI()
        requestOAthLogin()
    }
    
    private func setNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
        
        navigationItem.title = "微博登录"
    
    }
    
    @objc private func cancelAction() {
        
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '18703426351';document.getElementById('passwd').value = 'fy1523'")
        
    }
    //  请求第三方登录页面
    private func requestOAthLogin() {
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        
        print(url)
        
        let urlRequest = NSURLRequest(URL: NSURL(string: url)!)
        
        webView.loadRequest(urlRequest)
    
    }
    

    
}


// MARK: - UIWebViewDelegate 代理
extension FYOAuthViewController: UIWebViewDelegate {
    
    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString)
        
        guard let url = request.URL else {
            return false
        }
        
        //  不是以回调页打头,不需要关心
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri){
            return true
        }
        
        if let query = url.query where query.hasPrefix("code=") {
            print(query)
            
            let code = query.substringFromIndex("code=".endIndex)
            print(code)
            
            FYUserAccountViewModel.sharedUserAccount.reqeustAccessTokenWithCode(code, callBack: { (isSuccess) -> () in
                
                if isSuccess {
                    print("登录成功")
                    self.dismissViewControllerAnimated(false, completion: { () -> Void in
                          NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    })
                  
                    
                } else {
                    print("登录失败")
                }
            })
            
        } else {
            dismissViewControllerAnimated(true, completion: nil)
        }
        return false
        
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
}


